package com.ruoyi.business.weipinhuiController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.vo.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ownWPHApi")
public class WeiPinHuiController {

    @Autowired
    private RedisCache redisCache;

    private final static String CLASSESEN = "weipinhui";

    private final static String CALLBACK_URLBASE = "http://c2.wkanx.com/tracking";





    /**
     * http://47.94.2.84:9185/ownWPHApi/rta?channelId=6476246985869312&dmpid=__SID__&sid=__SID__&oaid=__OAID__&imei=__IMEI__&imei_md5=__HASH_IMEI__&idfa=__IDFA__&idfa_md5=__HASH_IDFA__
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "唯品会", businessType = BusinessType.RTA, esIndex = "weipinhui_log", saveType = SaveType.ES)
    @RequestMapping("/rta")
    public Object rtaSend(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);

        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }
        String url = channelDetail.get("rta_adress") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);



        String imeiMd5 = getMapValue(baseParamsMap, "imei_md5");
        String imei = getMapValue(baseParamsMap, "imei");
        String oaid = getMapValue(baseParamsMap, "oaid");
        String idfa = getMapValue(baseParamsMap, "idfa");
        String oaidMd5 = getMapValue(baseParamsMap, "oaid_md5");
        String idfaMd5 = getMapValue(baseParamsMap, "idfa_md5");
        if(StringUtils.isNotBlank(imeiMd5) && !"null".equals(imeiMd5) && !"__HASH_IMEI__".equals(imeiMd5)) {
            baseParamsMap.put("did", imeiMd5);
            baseParamsMap.put("didType", 0);
        }else if(StringUtils.isNotBlank(imei) && !"null".equals(imei) && !"__IMEI__".equals(imei)) {
           baseParamsMap.put("did", DigestUtils.md5DigestAsHex(imei.getBytes()));
            baseParamsMap.put("didType", 0);
        }else if(StringUtils.isNotBlank(oaid) && !"null".equals(oaid) && !"__OAID__".equals(oaid)) {
            baseParamsMap.put("did", oaid);
            baseParamsMap.put("didType", 1);
        }else if(StringUtils.isNotBlank(idfa) && !"null".equals(idfa) && !"__IDFA__".equals(idfa)) {
            baseParamsMap.put("did", idfa);
            baseParamsMap.put("didType", 2);
        }else if(StringUtils.isNotBlank(oaidMd5) && !"null".equals(oaidMd5) && !"__HASH_OAID__".equals(oaidMd5)) {
            //oaidMd5 在wifi RTA中没有宏替换
            baseParamsMap.put("did", oaidMd5);
            baseParamsMap.put("didType", 3);
        }else if(StringUtils.isNotBlank(idfaMd5) && !"null".equals(idfaMd5) && !"__HASH_IDFA__".equals(idfaMd5)) {
            baseParamsMap.put("did", idfaMd5);
            baseParamsMap.put("didType", 4);
        }

        // baseParamsMap 转jsonObject
        JSONObject reqJson = new JSONObject(baseParamsMap);
        reqJson.put("id", dmpid);

        String adReqs = getMapValue(baseParamsMap, "adReqs");
        if(StringUtils.isNotBlank(adReqs) && !"null".equals(adReqs)){
            reqJson.put("adReqs", JSONObject.parse(adReqs));
        }


        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }

        String reportResultsStr = "";
        reportResultsStr = HttpUtils.sendPostBody(requestAddress, reqJson.toJSONString() , ip, ua);
        System.out.println("ownWPHApi上报地址："+requestAddress);
        System.out.println("ownWPHApi上报参数："+reqJson.toJSONString());
        System.out.println("ownWPHApi返回结果："+reportResultsStr);

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
            if(reportResults.getInteger("errno") == 0){
                JSONArray jsonArray = reportResults.getJSONObject("bidResp").getJSONArray("adResps");
                String ac = jsonArray.getJSONObject(0).getString("ac");
                if("y".equals(ac)){
                    return 1;
                }
                return 0;
            }
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public static void main(String[] args) {
        String reportResultsStr= "{\"bidResp\":{\"adResps\":[{\"ac\":\"y\",\"token\":\"mingmei_xinke\"}],\"bidId\":\"231aca670d8d3d6d\",\"id\":\"3d9ecc4c79a6fc0d354d040c32a1d747\",\"resType\":0},\"errno\":0,\"msg\":\"success\"}";
        System.out.println(reportResultsStr);
        try{
            JSONObject reportResults = JSONObject.parseObject(reportResultsStr);
            if(reportResults.getInteger("errno") == 0){
                JSONArray jsonArray = reportResults.getJSONObject("bidResp").getJSONArray("adResps");
                String ac = jsonArray.getJSONObject(0).getString("ac");
                if("y".equals(ac)){
                    System.out.println(1);
                }
                System.out.println(0);
            }
        }catch (Exception e){
            System.out.println(0);
        }
    }


    /**
     * 唯品会未给出下游，无法编写回调逻辑。
     */

    /**
     * http://47.94.2.84:9185/ownWPHApi/send?channelId=6476246985869312&dmpid=__SID__&click_id=__SID__&idfa=__PLAIN_IDFA__&idfa_md5=__IDFA__&imei_md5=__IMEI__&oaid=__OAID__&oaid_md5=__HASH_OAID__&os=__OS__&ts=__STIME__&mac=__PLAIN_MAC__&cid=__CID__&click_ip=&user_agent=
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "唯品会", businessType = BusinessType.ESCALATION, esIndex = "weipinhui_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);

        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);


        String ua = baseParamsMap.get("user_agent") + "";
        String ip = baseParamsMap.get("click_ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }


        String callbackClientId = channelDetail.get("callback_clientid") + "";
        String callbackSecretkey = channelDetail.get("callback_secretkey") + "";
        String idfaMd5 = getMapValue(baseParamsMap, "idfa_md5");
        String imeiMd5 = getMapValue(baseParamsMap, "imei_md5");
        String mac = getMapValue(baseParamsMap, "mac");
        String os = getMapValue(baseParamsMap, "os");


        LinkedHashMap<String, String> callbackMap = new LinkedHashMap<>();
        callbackMap.put("cid", getMapValue(baseParamsMap, "cid"));
        callbackMap.put("clientid", callbackClientId);
        callbackMap.put("clientkey", callbackSecretkey);
        callbackMap.put("idfa", idfaMd5);
        callbackMap.put("imei", imeiMd5);
        //下游的mac是进行MD5加密过的就是上游的mac_md5
        callbackMap.put("mac", mac);
        callbackMap.put("os", os);
        //sid是下游给的click_id。 代表请求标识
        callbackMap.put("sid", getMapValue(baseParamsMap, "click_id"));
        //stime为上报时间戳。 上传过来的参数为ts
        callbackMap.put("stime", getMapValue(baseParamsMap, "ts"));

        List<String> tempList = new ArrayList<>();
        for(String key: callbackMap.keySet()){
            tempList.add(key+"="+callbackMap.get(key));
        }
        String callbackParams = String.join("&", tempList);
        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownWPHApi/callback/"+channelId+"/"+dmpid+"/";
        String encrypt_u = encrypDES.encrypt(CALLBACK_URLBASE);
        String nu = callbackBase + encrypt_u + "?"+callbackParams;
        baseParamsMap.put("callback_url", URLEncoder.encode(nu, Constants.UTF8));


        if(StringUtils.isNotBlank(idfaMd5) && !"null".equals(idfaMd5) && !"__IDFA__".equals(idfaMd5)) {
            baseParamsMap.put("idfa_md5", idfaMd5.toLowerCase());
        }
        if(StringUtils.isNotBlank(imeiMd5) && !"null".equals(imeiMd5) && !"__IMEI__".equals(imeiMd5)) {
            baseParamsMap.put("imei_md5", imeiMd5.toLowerCase());
        }

        String ts = getMapValue(baseParamsMap, "ts");
        if(StringUtils.isNotBlank(ts) && !"null".equals(ts) && !"__STIME__".equals(ts)) {
            // wifi ts为毫秒，上游唯品会需要毫秒
            baseParamsMap.put("click_time", ts+"000");
        }

        if("0".equals(os)){
            //安卓
            baseParamsMap.put("device_type", "2");
        }else if("1".equals(os)){
            //ios
            baseParamsMap.put("device_type", "1");
        }


        tempList = new ArrayList<>();
        for(String key: baseParamsMap.keySet()){
            String value = baseParamsMap.get(key) + "";
            if(value.startsWith("__") && value.endsWith("__")){
                value = "";
            }
            tempList.add(key+"="+value);
        }
        String requestParameters = String.join("&", tempList);
        String reportResultsStr = "";
        if("POST".equals(requestType)){
            reportResultsStr = HttpUtils.sendPost(requestAddress, requestParameters, ip, ua);
        }else{
            reportResultsStr = HttpUtils.sendGet(requestAddress, requestParameters, ip, ua);
        }
        System.out.println("ownWPHApi上报地址："+requestAddress);
        System.out.println("ownWPHApi上报参数："+requestParameters);
        System.out.println("ownWPHApi返回结果："+reportResultsStr);

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
            return reportResults==null?"":reportResults;
        }catch (Exception e){
            e.printStackTrace();
        }
        return reportResultsStr;
    }




    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }


    @Log(title = "唯品会", businessType = BusinessType.CALLBACK, esIndex = "weipinhui_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object callback(HttpServletRequest request, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        String queryString = request.getQueryString();
        Map<String, Object> queryMap = GetUrlParam.queryStrToMap(queryString);
        String eventType = queryMap.get("action_type") + "";
        if("ACTIVE".equals(eventType)){
            queryMap.put("event_type", 1);
        }else if("LAUNCH".equals(eventType)) {
            queryMap.put("event_type", 6);
        }else if("ADD_CART".equals(eventType) || "NEW_ORDER".equals(eventType) || "OLD_ORDER".equals(eventType)) {
            queryMap.put("event_type", 3);
        }else {
            queryMap.put("event_type", 1);
        }

        LinkedHashMap<String, String> callbackMap = new LinkedHashMap<>();
        callbackMap.put("cid", getMapValue(queryMap, "cid"));
        callbackMap.put("clientid", getMapValue(queryMap, "clientid"));
        callbackMap.put("idfa", getMapValue(queryMap, "idfa"));
        //下游没有imei, 但是有imei_md5
        callbackMap.put("imei", getMapValue(queryMap, "imei"));
        //下游的mac是进行MD5加密过的就是上游的mac_md5
        callbackMap.put("mac", getMapValue(queryMap, "mac"));
        callbackMap.put("os", getMapValue(queryMap, "os"));
        //sid是下游给的click_id。 代表请求标识
        callbackMap.put("sid", getMapValue(queryMap, "sid"));
        //stime为上报时间戳。 上传过来的参数为ts
        callbackMap.put("stime", getMapValue(queryMap, "stime"));
        //获取当前时间戳 并转化为秒
        callbackMap.put("ts", (System.currentTimeMillis()/1000)+"");

        String callbackSecretkey = getMapValue(queryMap, "clientkey");
        List<String> tempList = new ArrayList<>();
        for(String key: callbackMap.keySet()){
            tempList.add(key+"="+callbackMap.get(key));
        }
        String callbackParams = String.join("&", tempList);
        String md5 = DigestUtils.md5DigestAsHex((callbackParams+callbackSecretkey).getBytes(Constants.UTF8)).toUpperCase();
        callbackParams = callbackParams + "&event_type="+getMapValue(queryMap, "event_type");
        queryString = callbackParams + "&sign="+md5;

        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);
        String resultStr = HttpUtils.sendGet(requestAddress, queryString);
        try {
            JSONObject resultJson = JSON.parseObject(resultStr);
            return resultJson==null?"":resultJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }

}
